#!/usr/bin/env python
#-*-coding:utf-8-*-

import os
import urwid
import database
import threading, time

class FocusFrame(urwid.Frame):
  def keypress(self, size, key):
    if key == 'tab':
      focus_list = ('header','body','footer')
      focus_idx = focus_list.index(self.focus_part)
      for i in range(2):
        focus_idx = (focus_idx + 1) % len(focus_list)
        focus_name = focus_list[focus_idx]
        widget = getattr(self,'_'+focus_name)
        if widget!=None and widget.selectable():
          self.set_focus(focus_name)
    return urwid.Frame.keypress(self, size, key)

class Window():
  def __init__(self, parent, foot_buttons, table, id, con, editor_text, getterms=None):
    self.parent = parent
    self.foot_buttons = foot_buttons
    self.table = table
    self.id = id
    self.con = con
    self.editor_text = editor_text
    self.getterms = getterms

    self.begin()
    self.make_body()
    self.make_foot_buttons()
    self.end()
  
  def begin(self):
    self.head = [urwid.Text(self.parent.title), urwid.Divider('=')] 
    self.body = []
    self.foot = []
    
  def make_body(self):
    pass
    
  def make_foot_buttons(self):
    for e in self.foot_buttons:
      button = urwid.Button(e[1])
      exec compile("urwid.connect_signal(button, 'click', "+e[0]+", self.id)", "<string>", "exec")
      self.foot.append(urwid.AttrMap(button, None, focus_map='reversed'))
  
  def end(self):
    self.foot = urwid.Pile([urwid.Divider('='), urwid.Columns(self.foot, dividechars=4)])    
    h = urwid.Pile(self.head)
    b = urwid.Filler(urwid.Pile(self.body), 'top')
    frame = FocusFrame(b, header=h, footer=self.foot)
    self.parent.main.original_widget = urwid.Padding(frame, left=2, right=2)

  def return_to_main_menu(self, button, sx=None):
    self.parent.espeak.stop_speech()
    self.parent.main_menu(None)

class ListWindow(Window):
  def make_body(self):
    if type(self.table) == str:
      if self.id == None:
        l = self.parent.db.get_records(self.table)
        for e in l:
          button = urwid.Button(e[1])
          exec compile("urwid.connect_signal(button, 'click', "+self.con+", e[0])", "<string>", "exec")
          self.body.append(urwid.AttrMap(button, None, focus_map='reversed'))
      else:
        l = self.parent.db.get_records(self.table, terms=self.getterms)
        for e in l:
          button = urwid.Button(e[2])
          if self.con == None:
            exec compile("urwid.connect_signal(button, 'click', self.selected_list_item, e[0])", "<string>", "exec")
          else:
            exec compile("urwid.connect_signal(button, 'click', "+self.con+", e[0])", "<string>", "exec")
          self.body.append(urwid.AttrMap(button, None, focus_map='reversed'))
    else:
      for e in self.table:
        button = urwid.Button(e[1])
        exec compile("urwid.connect_signal(button, 'click', self.selected_list_item, e[0])", "<string>", "exec")
        self.body.append(urwid.AttrMap(button, None, focus_map='reversed'))

  def selected_list_item(self, button, id):
    self.parent.ret_data_proc(id)

      
class EditWindow(Window):
  def make_body(self):
    self.edit = urwid.Edit(self.editor_text)
    self.body.append(urwid.AttrMap(urwid.LineBox(self.edit), None, focus_map='reversed'))

  def done_edit_text(self, button, sid=None):
    self.parent.ret_data_proc(self.edit.get_edit_text())

  def clear_edit_text(self, button, sid=None):
    self.edit.set_edit_text("")
      
class MlEditWindow(EditWindow):
  def make_body(self):
    self.edit = urwid.Edit(u"", multiline=True)
    self.edit.set_edit_text(self.editor_text)
    self.body.append(urwid.AttrMap(urwid.LineBox(self.edit), None, focus_map='reversed'))

  
class Coresh():
  def __init__(self, sd):
    self.state = "main"
    self.cache = []
    self.db = database.CykloryDB()
    self.espeak = sd
    self.espeak.start()
    self.title = u"Válassz egy műveletet!"
    self.main = urwid.Padding(None, left=2, right=2) 
    self.top = urwid.Overlay(self.main, urwid.SolidFill(u'\N{MEDIUM SHADE}'), 
      align='center', width=('relative', 90),
      valign='middle', height=('relative', 90),
      min_width=20, min_height=9)
    self.main_menu(None)
    urwid.MainLoop(self.top, palette=[('reversed', 'standout', '')]).run()
    
  def ret_data_proc(self, data, id=None):
    if self.state == "new_subject":
      self.db.insert_record("Subjects", data)
      self.main_menu(None)
    elif self.state == "new_curriculum":
      self.cache.append(data)
      self.state = "new_curriculum_state2"
      self.title = u"Tananyag típusának kiválasztása"
      foot_buttons = [
       ["self.return_to_main_menu",u"Mégse"],
       ["self.parent.exit_program",u"Kilépés"]
      ]
      ListWindow(self, foot_buttons, [['Walltexts','Szöveg'],['Dictionary','Szótár']], id, None, None)
    elif self.state == "new_curriculum_state2":
      self.cache.append(data)
      self.state = "new_curriculum_state3"
      self.title = u"Tananyag szövege"
      foot_buttons = [
       ["self.done_edit_text",u"Ok"],
       ["self.clear_edit_text",u"Törlés"],
       ["self.return_to_main_menu",u"Mégse"],
       ["self.parent.exit_program",u"Kilépés"]
      ]
      MlEditWindow(self, foot_buttons, None, id, None, "")
    elif self.state == "new_curriculum_state3":
      curtext = data
      self.db.insert_record("Curriculums", self.cache)
      curid = self.db.get_records("Curriculums", columns=["id"], terms=[["subject_id", self.cache[0]], ["name", self.cache[1]]])[0][0]
      self.db.insert_record("Walltexts", [self.cache[0], curid, data])
      self.subject_menu(None, self.cache[0])
    elif self.state == "curriculum":
#      self.cache.append(data)
      if data == "learning" or data == "modify":
        if data == "learning":
          self.state = "curriculum_state2"
        else:
          self.state = "curriculum_modify"
        foot_buttons = [
         ["self.done_edit_text",u"Módosít"],
         ["self.clear_edit_text",u"Törlés"],
         ["self.return_to_main_menu",u"Mégse"],
         ["self.parent.exit_program",u"Kilépés"]
        ]
        terms = [["subject_id", self.cache[0]],["curriculum_id", self.cache[1]]]
        text = self.db.get_records("Walltexts", ["txt"], terms)[0][0]
        if data == "learning":
          self.espeak.set_text(text)
        MlEditWindow(self, foot_buttons, None, id, None, text, "")
      elif data == "save":
        terms = [["subject_id", self.cache[0]],["curriculum_id", self.cache[1]]]
        text = self.db.get_records("Walltexts", ["txt"], terms)[0][0]
        file_name = "cur_"+str(self.cache[0]) + "_" + str(self.cache[1])+".txt"
        o = open(file_name, "w")
        o.write(text.encode("utf-8"))
        o.close()
        print " --- Szöveges állomány mentve ide: " + file_name + " ---"
        file_name2 = "cur_"+str(self.cache[0]) + "_" + str(self.cache[1])+".wav"
        os.system("espeak -m -v hu --stdout -f "+file_name+" >"+file_name2)
        print " --- Hangfájl mentve ide: " + file_name2 + " ---"
      else:
        print data
    elif self.state == "curriculum_modify":
      print " --- Módosítva! ---"      
      self.db.update_record("Walltexts", [self.cache[0], self.cache[1], data])
    elif self.state == "curriculum_state2":
      self.db.update_record("Walltexts", [self.cache[0], self.cache[1], data])
      self.espeak.stop_speech()
      self.espeak.set_text(data)
    else:
      print data, self.state

  def main_menu(self, button, id=None):
    self.state = "main"
    self.title = u"Főmenü"
    foot_buttons = [
    ["self.parent.new_subject_menu",u"Új tantárgy"],
    ["self.parent.exit_program",u"Kilépés"]
    ]
    ListWindow(self, foot_buttons, "Subjects", None, "self.parent.subject_menu", None)


  def subject_menu(self, button, id):
    self.state = "subject"
    self.title = u"Témakörök"
    self.cache = [id]
    foot_buttons = [
    ["self.parent.new_curriculum_menu",u"Új témakör"],
    ["self.parent.new_test_menu",u"Új teszt"],
    ["self.parent.test_menu",u"Teszt"],
    ["self.parent.main_menu",u"Vissza"],
    ["self.parent.exit_program",u"Kilépés"]
    ]
    ListWindow(self, foot_buttons, "Curriculums", id, "self.parent.curriculum_menu", None, getterms=[["subject_id", id]])


  def new_subject_menu(self, button, id=None):
    self.state = "new_subject"
    self.title = u"Új tárgy hozzáadása"
    foot_buttons = [
    ["self.done_edit_text",u"Ok"],
    ["self.clear_edit_text",u"Törlés"],
    ["self.return_to_main_menu",u"Mégse"],
    ["self.parent.exit_program",u"Kilépés"]
    ]
    EditWindow(self, foot_buttons, "Subjects", None, None, u"Új tárgy neve: ")


  def new_curriculum_menu(self, button, id):
    self.state = "new_curriculum"
    self.cache = [id]
    self.title = u"Új témakör hozzáadása"
    foot_buttons = [
    ["self.done_edit_text",u"Ok"],
    ["self.clear_edit_text",u"Törlés"],
    ["self.return_to_main_menu",u"Mégse"],
    ["self.parent.exit_program",u"Kilépés"]
    ]
    EditWindow(self, foot_buttons, None, id, None, u"Új témakör neve: ")

  def curriculum_menu(self, button=None, id=None):
    self.state = "curriculum"
    self.cache.append(id)
    self.title = u"Tanulás"
    foot_buttons = [
     ["self.return_to_main_menu",u"Mégse"],
     ["self.parent.exit_program",u"Kilépés"]
    ]
    ListWindow(self, foot_buttons, [['learning','Tanulás'], ['save','Mentés fájlba'],['speed','Sebesség beállítása'],['modify','Módosít'],['delete','Töröl']], id, None, None)


  def new_test_menu(self):
    pass

  def test_menu(self):
    pass

  def exit_program(self, button, id=None):
    self.espeak.exit_speech()
    raise urwid.ExitMainLoop()
